package imageViewHelper;

import android.view.MotionEvent;
import android.view.ScaleGestureDetector;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout.LayoutParams;

public class ImageViewDragableListener implements View.OnTouchListener{
	private ScaleGestureDetector scaleDetector;
	
	private LayoutParams imgLp;
	private ImageView img;
	
	float startPtX, startPtY;
	int startMarginLeft, startMarginTop;
	
	public ImageViewDragableListener(ImageView img){
		this.img = img;
		this.imgLp = (LayoutParams) img.getLayoutParams();
		
		startPtX = 0.0f;
		startPtY = 0.0f;
		startMarginLeft = imgLp.leftMargin;
		startMarginTop = imgLp.topMargin;
		
		this.scaleDetector = new ScaleGestureDetector(img.getContext(), new ScaleListener());
	}
	
	
	@Override
	public boolean onTouch(View v, MotionEvent event) {
		this.scaleDetector.onTouchEvent(event);
		
		switch(event.getAction()){
		case MotionEvent.ACTION_DOWN:
			this.startPtX = event.getRawX();
			this.startPtY = event.getRawY();
			this.startMarginLeft = imgLp.leftMargin;
			this.startMarginTop = imgLp.topMargin;
			break;
		
		case MotionEvent.ACTION_MOVE:
			imgLp.leftMargin = this.startMarginLeft + (int)(event.getRawX() - this.startPtX);
			imgLp.topMargin = this.startMarginTop + (int)(event.getRawY() - this.startPtY);
			img.setLayoutParams(imgLp);
			break;
		default:
			return false;
		}
		return true;
	}
	
	private class ScaleListener extends ScaleGestureDetector.SimpleOnScaleGestureListener {
        private float scaleFactor = 1.0f;
		@Override
        public boolean onScale(ScaleGestureDetector detector) {
			scaleFactor *= detector.getScaleFactor();
            
			scaleFactor = Math.max(0.1f, 1.0f);
			
			ImageViewResizeHandler.resizeImageView(img, scaleFactor);
            return true;
        }
    }
}
